/*
 * @Author: XiaoHe
 */
/*
 * @Author: XiaoHe
 */
/*
 * @Author: XiaoHe
 */
package cn.he4966.xiaohepdf;


import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.rendering.ImageType;
import org.apache.pdfbox.rendering.PDFRenderer;
 
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.ArrayList;


public class PdfToImageService {


    public List<String> convertPdfToImages(String pdfFilePath, String outputDir ,Integer dpi,String bug) throws IOException {
        System.out.println("PDF转图片开始");
        File pdfFile = new File(pdfFilePath);
        PDDocument document = PDDocument.load(pdfFile);
        PDFRenderer pdfRenderer = new PDFRenderer(document);
        // 创建输出目录
        Files.createDirectories(Paths.get(outputDir));

        
        //把文件名字
        List<String> imageStrings = new ArrayList<>();
        for (int page = 0; page < document.getNumberOfPages(); ++page) {
            // 判断bug字符串不等于false
            if(bug.equals("false")){
                BufferedImage bim = pdfRenderer.renderImageWithDPI(page, dpi, ImageType.RGB);
                ImageIO.write(bim, "JPEG", new File(outputDir + "/page_" + (page + 1) + ".jpg"));
                //往imageStrings数组中添加"/page-" + (page + 1) + ".jpg"
                
            }
            imageStrings.add("/page_" + (page + 1) + ".jpg");
        }
        System.out.println("PDF转图片完成");

        document.close();
        return imageStrings;
    }
}
